package com.like.sortlist;

import java.util.List;
import java.util.Locale;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SectionIndexer;

import com.daimajia.swipe.adapters.BaseSwipeAdapter;

public abstract class BaseSortSwipeAdapter extends BaseSwipeAdapter implements
		SectionIndexer {

	protected List<BaseSort> mSorts;

	public BaseSortSwipeAdapter(List<BaseSort> sorts) {
		this.mSorts = sorts;
	}

	@Override
	public int getCount() {
		return mSorts.size();
	}

	@Override
	public Object getItem(int position) {
		return mSorts.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public void fillValues(int position, View convertView) {
		BaseSort sort = mSorts.get(position);
		int section = getSectionForPosition(position);
		if (section != -1) {
			if (position == getPositionForSection(section))
				showLetterHeader(convertView, sort);
			else
				hideLetterHeader(convertView);
		}
	}

	@Override
	public View generateView(int position, ViewGroup parent) {
		View view = showView(position, parent);
		return view;
	}

	@Override
	public Object[] getSections() {
		return null;
	}

	protected abstract View showView(int position, ViewGroup parent);

	protected abstract void hideLetterHeader(View convertView);

	protected abstract void showLetterHeader(View convertView, BaseSort sort);

	@Override
	public int getPositionForSection(int sectionIndex) {
		for (int i = 0; i < getCount(); i++) {
			String sortStr = mSorts.get(i).sortLetters;
			if (TextUtils.isEmpty(sortStr))
				continue;
			char firstChar = sortStr.toUpperCase(Locale.getDefault()).charAt(0);
			if (firstChar == sectionIndex) {
				return i;
			}
		}
		return -1;
	}

	@Override
	public int getSectionForPosition(int position) {
		if (TextUtils.equals("", mSorts.get(position).sortLetters))
			return -1;
		return mSorts.get(position).sortLetters.charAt(0);
	}

}
